<template>
  <div class="auth_video_page">
    <div class="box">
      <div id="videos-container"></div>
      <div class="experiment">
        <van-button type="info" @click="openCamera">打开摄像头</van-button>
        <van-button type="info" @click="startRecord">开始录制</van-button>
        <van-button type="info" @click="saver">提交</van-button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      a: 1,
      mediaRecorder: '',
      mediaStream: '',
      stopRecordCallback: '',
      recorderFile: ''
    };
  },
  methods: {
    openCamera() {
      const videosContainer = document.getElementById('videos-container');
      const len = videosContainer.childNodes.length;
      for (let i = 0; i < len; i += 1) {
        videosContainer.removeChild(videosContainer.childNodes[i]);
      }
      const video = document.createElement('video');
      const videoWidth = 320;
      const videoHeight = 240;
      video.controls = false;
      video.muted = true;
      video.width = videoWidth;
      video.height = videoHeight;
      this.getUserMedia({ facingMode: 'user' }, false, (err, stream) => {
        if (err) {
          throw err;
        }
        this.mediaRecorder = new MediaRecorder(stream);
        this.mediaStream = stream;
        let chunks = [];
        // const startTime = 0;
        video.srcObject = stream;
        video.play();
        videosContainer.appendChild(video);
        this.mediaRecorder.ondataavailable = (e) => {
          this.mediaRecorder.blobs.push(e.data);
          chunks.push(e.data);
        };
        this.mediaRecorder.blobs = [];
        this.mediaRecorder.onstop = (e) => {
          console.log(e);
          console.log(chunks);
          const clipContainer = document.createElement('article');
          const audio = document.createElement('audio');
          audio.controls = true;
          clipContainer.appendChild(audio);
          videosContainer.appendChild(clipContainer);
          // this.recorderFile = new Blob(chunks, { type: 'audio/ogg; codecs=opus' });
          const blob = new Blob(chunks, { type: 'audio/wav' });
          const audioURL = URL.createObjectURL(blob);
          audio.src = audioURL;
          chunks = [];
          if (this.stopRecordCallback !== null) {
            this.stopRecordCallback();
          }
        };
        console.log(err, stream);
      });
    },
    startRecord() {
      this.mediaRecorder.start();
      setTimeout(() => {
        this.stopRecord(() => {
          this.$toast('录制成功');
          console.log(1);
        });
      }, 5000);
    },
    saver() {
      console.log(this.recorderFile);
      // const blob = new Blob([this.recorderFile], { type: 'audio/wav' });
      this.$toast.success('提交成功');
    },
    stopRecord(callback) {
      this.stopRecordCallback = callback;
      this.mediaRecorder.stop();
      this.closeStream();
    },
    getUserMedia(videoEnable, audioEnable, callback) {
      navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia
        || navigator.mozGetUserMedia || navigator.msGetUserMedia || window.getUserMedia;
      const constraints = { video: videoEnable, audio: audioEnable };
      if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices.getUserMedia(constraints).then((stream) => {
          callback(false, stream);
        }).catch((err) => {
          callback(err);
        });
      } else if (navigator.getUserMedia) {
        navigator.getUserMedia(constraints, (stream) => {
          callback(false, stream);
        }, (err) => {
          callback(err);
        });
        console.log(2);
      } else {
        callback(new Error('Not support userMedia'));
      }
    },
    closeStream() {
      const stream = this.mediaStream;
      if (typeof stream.stop === 'function') {
        stream.stop();
      } else {
        const trackList = [stream.getAudioTracks(), stream.getVideoTracks()];
        for (let i = 0; i < trackList.length; i += 1) {
          const tracks = trackList[i];
          if (tracks && tracks.length > 0) {
            for (let j = 0; j < tracks.length; j += 1) {
              const track = tracks[j];
              if (typeof track.stop === 'function') {
                track.stop();
              }
            }
          }
        }
      }
    }
  },
  created() {
    // this.getUserMedia(true, true);
  }
};
</script>

<style lang="less">
.auth_video_page {
  height: 100%;
  .box {
    height: 100vw;
    /*background-color: #ccc;*/
    #videos-container {
      text-align: center;
      width: 100vw;
      height: 300PX;
      background-color: #ccc;
    }
    .experiment {
      text-align: center;
    }
  }
}
</style>
